package com.tomtop.core.redis;

import java.util.LinkedList;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class  LongRedisTemplate extends RedisTemplate<String, Long>{
	private final static  byte[] bytes;
	private final static int len;
	static{
		len=256;
		bytes=new byte[len];
		for (int i = 0; i < len; i++) {
			bytes[i] = (byte)(i-128);
		}
	}
	
	private final static RedisSerializer<String> stringSerializer = new StringRedisSerializer();
	private final static RedisSerializer<Long> longSerializer = new RedisSerializer<Long>() {
		
		public byte[] serialize(Long l) {
			if(l==null)return null;
			LinkedList<Byte> list=new LinkedList<>();
			do {
				list.addFirst(bytes[(int) (l%len)]);
			} while ((l=l/len)!=0);
			byte[] bytes=new byte[list.size()];
			for (int i = 0; i < bytes.length; i++) {
				bytes[i]=list.get(i);
			}
			return bytes;
		}
		public Long deserialize(byte[] _bytes) {
			if(_bytes==null)return null;
			long l=0; 
			for (Byte byte1 : _bytes) {
				for (int i = 0; i < bytes.length; i++) {
					if(bytes[i]==byte1){
						l=l*len+i;
						break;
					}
				}
			}
			return l;
		}
	};
	
	public LongRedisTemplate() {
		setKeySerializer(stringSerializer);
		setValueSerializer(longSerializer);
		setHashKeySerializer(stringSerializer);
		setHashValueSerializer(longSerializer);
	}
	public LongRedisTemplate(RedisConnectionFactory connectionFactory) {
		this();
		setConnectionFactory(connectionFactory);
		afterPropertiesSet();
	}
	protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
		return new DefaultStringRedisConnection(connection);
	}
}
